/*
Copyright SecureKey Technologies Inc. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/
package iampvdr

import (
	"strings"

	iamimpl "git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/ichain/iam"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/providers/core"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/providers/iam"
	"git.cloud.inspur.com/ichain/ichain-sdk-go/pkg/providers/ichain"
	"github.com/pkg/errors"
)

type IAMProvider struct {
	providerContext core.Providers
	userStore       iam.UserStore
	identityManager map[string]iam.IdentityManager
}

func New(endpointConfig ichain.EndpointConfig, cryptoSuite core.CryptoSuite, userStore iam.UserStore) (*IAMProvider, error) {

	identityManager := make(map[string]iam.IdentityManager)
	netConfig := endpointConfig.NetworkConfig()
	for orgName := range netConfig.Organizations {
		mgr, err := iamimpl.NewIdentityManager(orgName, userStore, cryptoSuite, endpointConfig)
		if err != nil {
			return nil, errors.Wrapf(err, "failed to initialize identity manager for organization: %s", orgName)
		}
		identityManager[orgName] = mgr
	}

	iamProvider := IAMProvider{
		userStore:       userStore,
		identityManager: identityManager,
	}

	return &iamProvider, nil
}

func (p *IAMProvider) Initialize(providers core.Providers) error {
	p.providerContext = providers
	return nil
}

func (p *IAMProvider) UserStore() iam.UserStore {
	return p.userStore
}

func (p *IAMProvider) IdentityManager(orgName string) (iam.IdentityManager, bool) {
	im, ok := p.identityManager[strings.ToLower(orgName)]
	if !ok {
		return nil, false
	}
	return im, true
}
